//
//  NetworkingHandle.m
//  UI29_Block
//
//  Created by dllo on 16/1/21.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "NetworkingHandle.h"
#import "AFNetworking.h"
#import <CommonCrypto/CommonDigest.h>
#import "Reachability.h"
@implementation NetworkingHandle


+ (void)networkingWithURL:(NSString *)string withIndex:(NSInteger)index completeHandel:(void (^)(NSURLResponse *response, NSData *data, NSInteger indexInsert))block{

    
    // 字符串转码
    NSString *codeStr = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    NSURL *url = [NSURL URLWithString:codeStr];
    
    // session
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        // 回到主线程(GCD).
        dispatch_async(dispatch_get_main_queue(), ^{
            
            // 如果有数据, 再执行
            if (data) {
           
                
                // 调用 block
                block(response, data, index);
                
            }
            
        });
        
    }];
    
    [dataTask resume];
}









+ (void)networkingWithURL:(NSString *)string completeHandel:(void (^)(NSURLResponse *response, NSData *data, id result))block{

    BOOL isExistenceNetwork = YES;
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    
    switch ([reach currentReachabilityStatus]) {
        case NotReachable:{
            isExistenceNetwork = NO;
            NSLog(@"没网");
            break;
        }
        case ReachableViaWiFi:{
            isExistenceNetwork = YES;
            break;
        }
        case ReachableViaWWAN:{
            isExistenceNetwork = YES;
            break;
        }
    }if (isExistenceNetwork) {
        
        // 将字符串进行转码 (URL 中不能含有中文等字符 )
        //NSString *temp = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:string]];
        
        /** 方法post */
        request.HTTPMethod = @"GET";
        /** body如果是get可为空 */
        request.HTTPBody = nil;
        
        // session
        NSURLSession *session = [NSURLSession sharedSession];
        //
        NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            
            if (data) {
                
                
                NSString *cook = @"cook/";
                NSString *behind = @".data";
                NSString *libPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
                
                
                
                NSString* path =[libPath stringByAppendingPathComponent:[cook stringByAppendingFormat:@"%@%@", [NetworkingHandle md5HexDigest:string],behind]];
                //  NSLog(@"%@", [NetworkingHandler md5HexDigest:string]);
                [data writeToFile:path  atomically:YES];
                NSLog(@"-------%@", path);
                // 数据解析
                id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                
                // 调用 block
                // 回到主线程(GCD)
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    block(response, data, result);
                    
                });
                
                
            }
            
            
        }];
        
        [task resume];
        
        
        
    }else {
        NSLog(@"没有网络(断网)");
        NSString *cook = @"cook/";
        NSString *behind = @".data";
        NSString *file = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        
        
        NSString* path =[file stringByAppendingPathComponent:[cook stringByAppendingFormat:@"%@%@", [NetworkingHandle md5HexDigest:string],behind]];
        
        NSMutableData *data = [NSMutableData dataWithContentsOfFile:path];
        
        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
     
        
        block(nil, nil, result);
    }
    
}

/** md5加密 */
+ (NSString *)md5HexDigest:(NSString*)input {
    const char* str = [input UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (unsigned int)strlen(str), result);
    
    NSMutableString *hash = [NSMutableString string];
    for (int i = 0; i < 16; i++)
    {
        [hash appendFormat:@"%02X", result[i]];
    }
    NSString *mdfiveString = [hash lowercaseString];
    
    return mdfiveString;
}









//

//+ (void)networkingWithURL:(NSString *)string completeHandel:(void (^)(NSURLResponse *, NSData *, id))block{
//
//    // 字符串转码
//    NSString *codeStr = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
//    
//    NSURL *url = [NSURL URLWithString:codeStr];
//    
//    // session
//    NSURLSession *session = [NSURLSession sharedSession];
//    NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//        
//        // 回到主线程(GCD).
//        dispatch_async(dispatch_get_main_queue(), ^{
//            
//            // 如果有数据, 再执行
//            if (data) {
//             
//                // 数据解析
//                id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
//            
//                // 调用 block
//                block(response, data, result);
//                
//            }
//            
//        });
//      
//    }];
//    
//    [dataTask resume];
//}


@end
